//
//  LoadWebViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/4/9.
//

import UIKit
import WebKit
class LoadWebViewController: CommonViewController {
    var url:String = ""
    private let progress = UIProgressView()
    private var web = WKWebView()
    private var aitems:Array<UIBarButtonItem> = []
    private var bitems:Array<UIBarButtonItem> = []
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(web)
        web.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        let config = WKWebViewConfiguration.init()
        web = WKWebView.init(frame: CGRect.zero, configuration: config)
        let user = web.configuration.userContentController
        user.add(self, name: "ss")
        web.load(URLRequest.init(url: URL.init(string: self.url)!))        
        web.uiDelegate = self
        web.navigationDelegate = self
        // 添加进度条
        view.addSubview(progress)
        progress.tintColor = .blue
        progress.progress = 0.0
        progress.snp.makeConstraints({
            $0.left.right.equalTo(0)
            $0.height.equalTo(2)
            
            if #available(iOS 11.0, *) {
                $0.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            } else {
                // Fallback on earlier versions
                $0.top.equalToSuperview()
            }
        })
        
        // kvo 添加观察
        web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        let closeitem = UIBarButtonItem.init(image: UIImage(named: "close"), style: .plain, target: self, action: #selector(closePage))
        let backitem = UIBarButtonItem.init(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(backBtnClick))
        self.aitems = [backitem,closeitem]
        self.bitems = [backitem]
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") {
            progress.alpha = 1
            progress.setProgress(Float(web.estimatedProgress), animated: true)
            if(self.web.estimatedProgress>=1.0){
                // 加载完成,隐藏进度条
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut) {
                    self.progress.alpha = 0
                } completion: {_ in
                    self.progress.progress = 0
                }
            }
        }
    }
    
    override func backBtnClick() {
        if(web.canGoBack){
            web.goBack()
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func closePage() {
        self.navigationController?.popViewController(animated: true)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    

}
extension LoadWebViewController:WKScriptMessageHandler{
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}
extension LoadWebViewController:WKUIDelegate{
    // webview 初始化load配置
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 实现非安全链接的跳转,如果主视图不为空允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil){
            webView.load(navigationAction.request)
        }
        return nil
    }
    // webview 关闭时
    func webViewDidClose(_ webView: WKWebView) {
        
    }
    // 处理页面中的提示框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
    }
    // 处理页面中的确认框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        
    }
    // 处理页面中的输入框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
    }
    
}
extension LoadWebViewController:WKNavigationDelegate{

    // URL页面开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
    }
    // URL页面内容开始返回
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        
    }
    // URL页面加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.title = webView.title
        if(webView.canGoBack){
            // 导航栏添加关闭按钮
            self.navigationItem.leftBarButtonItems = self.aitems
        }else{
            self.navigationItem.leftBarButtonItems = self.bitems
        }
    }
    // URL页面开始加载数据时异常
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
    }
    // URL页面期间发生异常
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
    }
    // URL页面收到服务器跳转请求
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
    }
    // 收到响应后, 是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        // 默认允许
        decisionHandler(.allow)
    }
    
    // 进程终止时
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        
    }
    // 发送请求前是否跳转
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 默认允许
        decisionHandler(.allow)
    }
    @available(iOS 13.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        decisionHandler(.allow,preferences)
    }
    // URL页面响应身份验证
    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(.useCredential,.none)
    }
    // URL页面使用不推荐的tls版本时
    @available(iOS 14.0, *)
    func webView(_ webView: WKWebView, authenticationChallenge challenge: URLAuthenticationChallenge, shouldAllowDeprecatedTLS decisionHandler: @escaping (Bool) -> Void) {
        decisionHandler(true)
    }
}
